import { defineStore } from 'pinia'
import { authService } from '../services/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false,
    loading: false,
    error: null
  }),

  getters: {
    isLoggedIn: (state) => state.isAuthenticated && !!state.token,
    currentUser: (state) => state.user
  },

  actions: {
    // 初始化认证状态
    initAuth() {
      const token = authService.getToken()
      const user = authService.getCurrentUser()
      
      if (token && user) {
        this.token = token
        this.user = user
        this.isAuthenticated = true
      }
    },

    // 用户注册
    async register(userData) {
      this.loading = true
      this.error = null
      
      try {
        const result = await authService.register(userData)
        
        if (result.success) {
          this.user = result.user
          this.token = result.token
          this.isAuthenticated = true
          return { success: true }
        } else {
          this.error = result.error
          return { success: false, error: result.error }
        }
      } catch (error) {
        this.error = '注册失败，请重试'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    },

    // 用户登录
    async login(credentials) {
      this.loading = true
      this.error = null
      
      try {
        const result = await authService.login(credentials)
        
        if (result.success) {
          this.user = result.user
          this.token = result.token
          this.isAuthenticated = true
          return { success: true }
        } else {
          this.error = result.error
          return { success: false, error: result.error }
        }
      } catch (error) {
        this.error = '登录失败，请重试'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    },

    // 用户登出
    logout() {
      authService.logout()
      this.user = null
      this.token = null
      this.isAuthenticated = false
      this.error = null
    },

    // 清除错误信息
    clearError() {
      this.error = null
    }
  }
})
